package com.firesrc.demo;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public abstract class Renderer {
  private ExecutorService executor = Executors.newFixedThreadPool(5);

  void execute(CharSequence source) throws Throwable {

    //第一种执行方式用executor直接执行
    Future<String> future = executor.submit(new CallTask("test"));
    String string = future.get();

    //第二种是生产者消费者模式的执行
    CompletionService<String> completionService = new ExecutorCompletionService<String>(executor);
    List<String> list = new ArrayList<String>();
    list.add("test1");

    //生产者提交请求
    for (final String imageInfo : list) {
      completionService.submit(new CallTask(imageInfo));
    }
    //    onIdelDoing(source);

    try {
      for (int t = 0, n = list.size(); t < n; t++) {
        //消费者获得请求,最先处理完的请求最先返回
        Future<String> f = completionService.take();
        String imageData = f.get();
        //        renderImage(imageData);
      }
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
    } catch (ExecutionException e) {
      throw new Throwable(e.getCause());
    }
  }

  private final class CallTask implements Callable<String> {

    public CallTask(String imageInfo) {
    }

    public String call() {
      return "test";
    }
  }

}
